﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;
using System.IO;
using System.Windows.Forms;
using TwitterLib;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Windows.Navigation;
using System.Windows.Threading;

namespace Common.Controls
{

    /// <summary>
    /// Viewer.xaml 的交互逻辑
    /// </summary>
    public partial class Viewer
    {

        private string _middlePic;
        private string _largePic;
        private Sinaurl_Info _urlInfo;
        private string _source;

        public string Source
        {
            get { return _source; }
            set { _source = value; }
        }

        public Sinaurl_Info UrlInfo
        {
            get { return _urlInfo; }
            set { _urlInfo = value; }
        }
        public string MiddlePic
        {
            get { return _middlePic; }
            set { _middlePic = value; }
        }
        public string LargePic
        {
            get { return _largePic; }
            set { _largePic = value; }
        }


        public Viewer(string _source)
        {
            if (_source != null)
            {
                Source = _source;
                MiddlePic = _source.Replace("thumbnail", "bmiddle");
                LargePic = _source.Replace("thumbnail", "large");
            }
            InitializeComponent();
            this.timer = new DispatcherTimer();
        }

        public Viewer(Sinaurl_Info _urlInfo)
        {
            this._urlInfo = _urlInfo;
            InitializeComponent();
            this.timer = new DispatcherTimer();
        }

        //private WebBrowserOverlay wbo;
        private VideoViewerOverlay videoVO;
        private string sinaMusicUrl = "http://music.sina.com.cn/yueku/js/mwp/changpianqiang.swf?color=14804199&songList=" + "&time=1300821766234";
        public void NavigateSinaMusic()
        {
            //string url = "http://music.sina.com.cn/yueku/m.php?id=" + UrlInfo.url.Substring(UrlInfo.url.LastIndexOf('/') + 1, 6);
            //System.Windows.Controls.WebBrowser wb = wbo.WebBrowser;
            //wb.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(wb_LoadCompleted);
            //wb.Navigate(url);
            string finalUrl = sinaMusicUrl.Insert(81, (
                sinaMusicUrl.Substring(81, sinaMusicUrl.LastIndexOf('&') + 1 - 81).Insert(0, UrlInfo.url.Substring(UrlInfo.url.LastIndexOf('/') + 1, UrlInfo.url.LastIndexOf('.') - UrlInfo.url.LastIndexOf('/')) + ',').Trim(',')

            ));
            videoVO.FlashShow.Movie = finalUrl;
            sinaMusicUrl = finalUrl;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (UrlInfo != null)
                {
                    if (UrlInfo.type == "video")
                    {
                        videoVO = new VideoViewerOverlay(VideoViewerGrid);
                        videoVO.FlashShow.Movie = UrlInfo.flash;
                        ImageViewerGrid.Visibility = Visibility.Collapsed;
                        MusicViewerGrid.Visibility = Visibility.Collapsed;
                        WebBrowserGrid.Visibility = Visibility.Collapsed;
                        VideoViewerGrid.Visibility = Visibility.Visible;
                        this.Title = UrlInfo.title;
                    }
                    else if (UrlInfo.type == "music")
                    {
                        if (UrlInfo.url.Remove(0, UrlInfo.url.LastIndexOf('.') + 1) == "mp3")
                        {
                            //MusicPlayer.Source = new Uri(UrlInfo.url);
                            ImageViewerGrid.Visibility = Visibility.Collapsed;
                            VideoViewerGrid.Visibility = Visibility.Collapsed;
                            WebBrowserGrid.Visibility = Visibility.Collapsed;
                            MusicViewerGrid.Visibility = Visibility.Visible;
                            this.Title = UrlInfo.title;
                        }
                        else
                        {
                            if (UrlInfo.url.Contains("music.sina.com.cn/yueku"))
                            {
                                //wbo = new WebBrowserOverlay(WebBrowserGrid);
                                //NavigateMusic();
                                videoVO = new VideoViewerOverlay(VideoViewerGrid);
                                //宽400 高330 从81开始插入
                                NavigateSinaMusic();
                                ImageViewerGrid.Visibility = Visibility.Collapsed;
                                VideoViewerGrid.Visibility = Visibility.Visible;
                                WebBrowserGrid.Visibility = Visibility.Collapsed;
                                MusicViewerGrid.Visibility = Visibility.Collapsed;
                            }
                        }
                    }
                }
                else if (MiddlePic != null)
                {
                    ImageViewerGrid.Visibility = Visibility.Visible;
                    MusicViewerGrid.Visibility = Visibility.Collapsed;
                    VideoViewerGrid.Visibility = Visibility.Collapsed;
                    WebBrowserGrid.Visibility = Visibility.Collapsed;
                    imageViewer.Source = MiddlePic;
                }
            }
            catch
            {
                this.Close();
            }
        }
        private void wb_LoadCompleted(object sender, NavigationEventArgs e)
        {
            System.Windows.Controls.WebBrowser wb = (System.Windows.Controls.WebBrowser)sender;
            mshtml.HTMLDocumentClass dom = (mshtml.HTMLDocumentClass)wb.Document;
            dom.documentElement.style.overflow = "hidden";
        }

        private void Resize_Click(object sender, RoutedEventArgs e)
        {
            imageViewer.ReSizeImage();
        }

        private void Rotate_Click(object sender, RoutedEventArgs e)
        {
            imageViewer.RePositionImage();
            imageViewer.RotateImage(90.0);
        }

        #region MusicPlayer音乐播放器相关操作

        private TimeSpan duration;
        private DispatcherTimer timer;

        private void MusicPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            //视频总时长
            double seconds = MusicPlayer.NaturalDuration.TimeSpan.TotalSeconds;
            //共分成10等分，每1等分多少秒
            timelineSlider.Maximum = seconds / 10;
            double baseSecond = seconds / timelineSlider.Maximum;
            this.timer.Interval = new TimeSpan(0, 0, 1);
            this.timer.Tick += new EventHandler(timer_Tick);
            this.timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.timelineSlider.ValueChanged -= new RoutedPropertyChangedEventHandler<double>(timelineSlider_ValueChanged);
            this.timelineSlider.Value = this.MusicPlayer.Position.TotalSeconds / 10.0;
            this.timelineSlider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(timelineSlider_ValueChanged);

            try
            {
                if (MusicPlayer.Position != TimeSpan.Zero)
                {
                    txtTime.Text = string.Format(
                                   "{0}{1:00}:{2:00}:{3:00}",
                                   "",
                                   MusicPlayer.Position.Hours,
                                   MusicPlayer.Position.Minutes,
                                   MusicPlayer.Position.Seconds);
                    txtTime.Text += "/";
                    txtTime.Text += string.Format(
                     "{0}{1:00}:{2:00}:{3:00}", "",
                    MusicPlayer.NaturalDuration.TimeSpan.Hours,
                    MusicPlayer.NaturalDuration.TimeSpan.Minutes,
                    MusicPlayer.NaturalDuration.TimeSpan.Seconds
                     );
                }
                //this.txtTime.Text = this.mediaElement.Position.Hours.ToString() + ":" + this.mediaElement.Position.Minutes.ToString() + ":" + this.mediaElement.Position.Seconds.ToString() + "/" + this.mediaElement.NaturalDuration.TimeSpan.Hours.ToString() + ":" + this.mediaElement.NaturalDuration.TimeSpan.Minutes.ToString() + ":" + this.mediaElement.NaturalDuration.TimeSpan.Seconds.ToString();
            }
            catch { }
        }

        private void MediaTimeChanged(object sender, EventArgs e)
        {
            timelineSlider.Value = MusicPlayer.Position.TotalMilliseconds;
        }

        private void MusicPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            MusicPlayer.Stop();
            timelineSlider.Value = 0;
            playBtn.Content = "播放";
            MusicPlayer.ToolTip = "点击播放";
        }


        private void timelineSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            TimeSpan span = new TimeSpan(0, 0, (int)(timelineSlider.Value) * 10);
            MusicPlayer.Position = span;
        }

        private void MusicPlayer_Loaded(object sender, RoutedEventArgs e)
        {
            if (UrlInfo != null)
            {
                if (UrlInfo.url.Remove(0, UrlInfo.url.LastIndexOf('.') + 1).Contains("mp3"))
                {
                    MusicPlayer.Source = new Uri(UrlInfo.url, UriKind.RelativeOrAbsolute);
                    playBtn.IsEnabled = true;
                }
            }
        }

        private void PlayerPause()
        {
            if (playBtn.Content.ToString() == "播放")
            {
                MusicPlayer.Play();
                playBtn.Content = "暂停";
            }
            else
            {
                MusicPlayer.Pause();
                playBtn.Content = "播放";
            }
        }

        private void playBtn_Click(object sender, RoutedEventArgs e)
        {
            PlayerPause();
        }

        private void stopBtn_Click(object sender, RoutedEventArgs e)
        {
            MusicPlayer.Stop();
            playBtn.Content = "播放";
        }

        private void mediaElement_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            PlayerPause();
        }

        #endregion

        private void Download_Click(object sender, RoutedEventArgs e)
        {
            string filename = LargePic.Remove(0, LargePic.LastIndexOf('/') + 1);
            SaveFileDialog sf = new SaveFileDialog();
            sf.FileName = filename;
            sf.DefaultExt = ".jpg";
            sf.AddExtension = true;
            sf.ShowDialog();
            if (sf.FileName != null)
            {
                WebClient client = new WebClient();
                client.DownloadFile(LargePic, sf.FileName);
            }
        }

        protected override Decorator GetWindowButtonsPlaceholder()
        {
            return WindowButtonsPlaceholder;
        }

        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
                this.DragMove();
        }

        private void volumeBtn_Click(object sender, RoutedEventArgs e)
        {
            if (volumeSlider.Visibility == Visibility.Collapsed)
            {
                volumeSlider.Visibility = Visibility.Visible;
            }
            else
            {
                volumeSlider.Visibility = Visibility.Collapsed;
            }
        }


    }

}
